<style lang="less">
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .border-card {
    margin-top: 20px;
  }
  .dialog-form-label{
    label{
      width: 120px;
    }

  }
  .dialog-form-content{
    width: 350px
  }
</style>

<template>
  <section>
    <el-tabs type="border-card" height="500px" class="border-card">
      <!--收货地址******************-->
      <el-tab-pane>
        <span slot="label">收货地址</span>
        <!--工具条-->
        <search-bar>
          <el-row>
            <el-col :span="4">
              <el-form-item label="关键字" :label-width="searchConditionLabelWidth">
                <el-select v-model="condition.keyword" placeholder="请选择查询关键字">
                  <el-option
                    v-for="(item,index) in keywords"
                    :label="item.label"
                    :value="item.value" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label-width="searchConditionLabelWidth2">
                <el-input  placeholder="请输入关键字" v-model="condition.keywordValue"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </search-bar>
        <!-- 搜索end -->
        <!-- 操作 -->
        <el-col :span="24" style="margin-bottom: 10px">
          <el-button type="primary" @click="createNewAddress('新增地址',addressTypeShip)">新增</el-button>
          <el-button type="danger" @click="handelBathDelete">批量删除</el-button>
          <el-button type="primary" @click="resetCondition" style="float: right">重置</el-button>
          <el-button type="primary" @click="handleSearch" style="float: right;margin-right: 10px">查询</el-button>
        </el-col>
        <!--操作end-->
        <!--列表-->
        <el-table :data="shipAddressData" highlight-current-row border style="width: 100%;" min-height="450"
                  max-height="450"
                  v-loading="listLoading"
                  @sort-change="sortChange"
                  @selection-change="selsChange">
          <el-table-column type="selection" width="50" align="center">
          </el-table-column>
          <!--<el-table-column prop="userId" width="50" align="center">-->
          <!--</el-table-column>-->
          <el-table-column prop="isDefault" label="默认" width="150" align="center" :formatter="defaultFormatter">
          </el-table-column>
          <el-table-column prop="contactName" label="收货人姓名" width="150" align="center" >
          </el-table-column>
          <el-table-column prop="contactPhone" label="手机号" width="200" align="center" >
          </el-table-column>
          <el-table-column prop="telephone" label="固定电话" width="200" align="center" >
          </el-table-column>
          <el-table-column prop="collectAddressName" label="详细地址" width="500" align="center" header-align="left">
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="150" align="center">
            <template slot-scope="scope">
              <el-button type="primary" v-if="scope.row.isDefault !== isDefaultTrue"
                         @click="setDefault(scope.$index, scope.row)">设为默认
              </el-button>
              <el-button type="primary" v-if="scope.row.isDefault === isDefaultTrue" disabled="disabled"
                         @click="setDefault(scope.$index,scope.row)">设为默认
              </el-button>
              <el-button type="primary" @click="getEditBYId('编辑地址',scope.$index,scope.row)">编辑</el-button>
              <el-button type="danger" @click="handelDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--列表工具条-->
        <el-col :span="24" class="toolbar">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total,sizes,prev, pager, next, jumper"
            :total="total" style="float: right">
          </el-pagination>
        </el-col>
      </el-tab-pane>
      <!--发货地址******************-->
      <el-tab-pane>
        <span slot="label">发货地址</span>
        <search-bar>
          <el-row>
            <el-col :span="4">
              <el-form-item label="关键字" :label-width="searchConditionLabelWidth">
                <el-select v-model="sendCondition.keyword" placeholder="请选择查询关键字">
                  <el-option
                    v-for="(item,index) in keywords"
                    :label="item.label"
                    :value="item.value" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label-width="searchConditionLabelWidth2">
                <el-input  placeholder="请输入关键字" v-model="sendCondition.keywordValue"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </search-bar>
        <!-- 搜索end -->
        <!-- 操作 -->
        <el-col :span="24" style="margin-bottom: 10px">
          <el-button type="primary" @click="createNewAddress('新增地址',addressTypeSend)">新增</el-button>
          <el-button type="danger" @click="sendHandelBathDelete">批量删除</el-button>
          <el-button type="primary" @click="sendResetCondition" style="float: right">重置</el-button>
          <el-button type="primary" @click="sendHandleSearch" style="float: right;margin-right: 10px">查询</el-button>
        </el-col>
        <!--操作end-->
        <!--列表-->
        <el-table :data="sendAddressData" highlight-current-row border style="width: 100%;" min-height="450"
                  max-height="450"
                  v-loading="sendListLoading"
                  @sort-change="sendSortChange"
                  @selection-change="sendSelsChange">
          <el-table-column type="selection" width="50" align="center">
          </el-table-column>
          <!--<el-table-column prop="userId" width="50" align="center">-->
          <!--</el-table-column>-->
          <el-table-column prop="isDefault" label="默认" width="150" align="center" :formatter="defaultFormatter">
          </el-table-column>
          <el-table-column prop="contactName" label="发货人姓名" width="150" align="center" >
          </el-table-column>
          <el-table-column prop="contactPhone" label="手机号" width="200" align="center" >
          </el-table-column>
          <el-table-column prop="telephone" label="固定电话" width="200" align="center" >
          </el-table-column>
          <el-table-column prop="collectAddressName" label="详细地址" width="500" align="center" header-align="left">
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="150" align="center">
            <template slot-scope="scope">
              <el-button type="primary" v-if="scope.row.isDefault !== isDefaultTrue"
                         @click="sendSetDefault(scope.$index, scope.row)">设为默认
              </el-button>
              <el-button type="primary" v-if="scope.row.isDefault === isDefaultTrue" disabled="disabled"
                         @click="sendSetDefault(scope.$index,scope.row)">设为默认
              </el-button>
              <el-button type="primary" @click="getEditBYId('编辑地址',scope.$index,scope.row)">编辑</el-button>
              <el-button type="danger" @click="sendHandelDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--列表工具条-->
        <el-col :span="24" class="toolbar">
          <el-pagination
            :current-page="sendCurrentPage"
            :page-size="sendPageSize"
            @size-change="sendHandleSizeChange"
            @current-change="sendHandleCurrentChange"
            layout="total,sizes,prev, pager, next, jumper"
            :total="sendTotal" style="float: right">
          </el-pagination>
        </el-col>
      </el-tab-pane>
    </el-tabs>
    <!--收货/发货地址的新增/修改页面****************-->
    <el-dialog :title="dialogTitle" @close="resetDialogForm" :visible.sync="dialogFormVisible" size="tiny">
      <el-form :key="dialogKey" :model="dialogForm" ref="dialogForm" :rules="rules">
        <el-form-item label="userId" class="dialog-form-label" style="display: none">
          <el-input v-model="dialogForm.userId" style="width: 220px" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址类型" class="dialog-form-label">
          <el-select v-model="dialogForm.addressType" disabled="disabled" class="dialog-form-content" placeholder="请选择地址类型">
            <el-option
              v-for="item in $store.getters.ADDRESS_TYPE"
              :key="item.dictVal"
              :label="item.cnDictValname"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="contactName" class="dialog-form-label">
          <el-input v-model="dialogForm.contactName" class="dialog-form-content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="contactPhone" class="dialog-form-label">
          <el-input v-model="dialogForm.contactPhone" class="dialog-form-content" auto-complete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="固话" prop="telephone" class="dialog-form-label">
          <el-input v-model="dialogForm.telephone" class="dialog-form-content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="addressSelect" class="dialog-form-label">
          <address-select v-model="dialogForm.addressSelect" style="width: 350px"
                          placeholder="请选择省、市、区县"
                          class="dialog-form-content"></address-select>
          <address-update-warn v-if="dialogForm.addressSelect && dialogForm.id && dialogForm.addressSelect[3] == null" >
          </address-update-warn>
        </el-form-item>
        <el-form-item label=" " prop="street" class="dialog-form-label">
          <el-input auto-complete="off" v-model="dialogForm.street" class="dialog-form-content"
                    placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="isDefault" class="dialog-form-label">
          <el-checkbox style="margin-left: 120px" v-model="dialogForm.isDefault" :true-label="isDefaultTrue" :false-label="isDefaultFalse">
            是否默认值
          </el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm(true)">取 消</el-button>
        <el-button type="primary" @click.native="handleSubmit(dialogForm.addressType)" :loading="submitLoading">提交
        </el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import AddressUpdateWarn from '../meb-user/AddressUpdateWarn.vue';
import {
  modifyIsDefault,
  batchAddressDel,
  saveAddress,
  searchAddresses
} from '../../api/meb-user/AddressManage';
import { isEmpty } from '../../lib/util';
export default{
  components: {
    AddressUpdateWarn
  },
  data () {
    return {
      // 通用属性*********************************************
      // 验证规则
      rules: {
        contactName: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
        ],
        contactPhone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur'}
        ],
        addressSelect: [
          {type: 'array', required: true, message: '请选择地址', trigger: 'blur'}
        ],
        street: [
          {required: true, message: '请输入详细地址', trigger: 'blur'}
        ]
      },
      keywords: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 'contactName',
          label: '姓名'
        }, {
          value: 'contactPhone',
          label: '手机号'
        }, {
          value: 'street',
          label: '地址'
        }
      ],

      userId: this.$store.state.userId,
      token: this.$store.state.token,
      dialogTitle: '新增地址',
      dialogFormVisible: false,
      dialogKey: null,
      dialogForm: {'addressSelect': []},
      searchConditionLabelWidth: '80px',
      searchConditionLabelWidth2: '20px',
      dialogFormLabelWidth: '120px',
      listLoading: false,
      submitLoading: false,
      // 字典值
      addressTypeShip: 109002001, // 收货地址
      addressTypeSend: 109002002, // 发货地址
      isDefaultTrue: 111002001, // 是
      isDefaultFalse: 111002002, // 否

      // 收货地址*************************
      condition: {
        keyword: 'contactName',
        keywordValue: ''
      },
      shipAddressData: [],
      sels: [],
      total: 30,
      currentPage: 1,
      pageSize: 10,
      sortProp: 'contactName',
      sortOrder: 'descending',

      // 发货地址****************************
      sendCondition: {
        keyword: 'contactName',
        keywordValue: ''
      },
      sendAddressData: [],
      sendListLoading: false,
      sendSubmitLoading: false,
      sendSels: [],
      sendTotal: 30,
      sendCurrentPage: 1,
      sendPageSize: 10,
      sendSortProp: 'contactName',
      sendSortOrder: 'descending'
    };
  },
  methods: {
    //* *****************************************************通用方法*********************
    // 列表默认地址打√
    defaultFormatter (row, column) {
      if (row.isDefault === 111002001) {
        return '√';
      } else {
        return '---';
      }
    },
    // 清空弹出框表单
    resetDialogForm (close = true) {
      if (close) {
        this.dialogFormVisible = false;
      }
      this.dialogForm.addressSelect = [];
      for (let p in this.dialogForm) {
        if (this.dialogForm[p] instanceof Array) {
          this.dialogForm[p] = [];
        } else {
          this.dialogForm[p] = null;
        }
      }
    },
    // 新增页面（同修改页面）
    createNewAddress (dialogTitle, addressType) {
      this.dialogKey = Math.random() - 0.5;
      this.dialogTitle = dialogTitle;
      this.dialogFormVisible = true;
      this.dialogForm.addressType = addressType;
      this.dialogForm.userId = this.userId;
      // this.dialogForm.isDefault = 111002002;
      this.dialogForm.country = '中国';
    },
    // 弹出修改页面
    getEditBYId (dialogTitle, index, row) {
      this.dialogKey = Math.random() - 0.5;
      this.dialogTitle = dialogTitle;
      this.dialogFormVisible = true;
      this.dialogForm = Object.assign({}, row);
      if (!isEmpty(this.dialogForm.provinceId)) {
        this.dialogForm.addressSelect = [this.dialogForm.provinceId, this.dialogForm.cityId, this.dialogForm.countyId, this.dialogForm.townId];
      }
    },

    //* *************************************************************收货地址**********************
    // 查询按钮
    handleSearch () {
      if (!isEmpty(this.condition.keyword) && isEmpty(this.condition.keywordValue)) {
        this.$message.error('请输入查询关键字！');
        return;
      }
      this.searchShipAddress();
    },
    // 搜索收货地址列表
    searchShipAddress () {
      this.listLoading = true;
      let params = 'addressType=109002001 g0;';// 地址类型(固定收货地址类型）
      // 关键字
      if (!isEmpty(this.condition.keyword) && !isEmpty(this.condition.keywordValue)) {
        if (this.condition.keyword === 'contactName') {
          params += 'contactName?' + this.condition.keywordValue + ' g1;';
        }
        if (this.condition.keyword === 'contactPhone') {
          params += 'contactPhone?' + this.condition.keywordValue + ' g1;';
        }
        if (this.condition.keyword === 'street') {
          params += 'collectAddressName?' + this.condition.keywordValue + ' g1;';
        }
      }
      params += 'userId=' + this.userId + ' g2;';
      searchAddresses({
        page: this.currentPage,
        size: this.pageSize,
        filters: params,
        sorts: (this.sortProp === null ? '' : (this.sortOrder === 'ascending' ? '-' : '+') + this.sortProp)
      }).then((res) => {
        this.listLoading = false;
        if (res.data.successFlg === true) {
          this.shipAddressData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
        } else {
          this.$message.error('查询失败！');
        }
      }).catch(() => {
        this.$message.error('数据有误，查询失败！');
        this.listLoading = false;
      });
    },
    // 排序改变
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchShipAddress();
    },
    // 多选框
    selsChange (sels) {
      this.sels = sels;
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchShipAddress();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchShipAddress();
    },
    // 重置查询条件
    resetCondition () {
      for (let p in this.condition) {
        this.condition[p] = null;
      }
    },
    // 批量删除
    handelBathDelete () {
      let id = this.sels.map(item => item.id);
      if (id === '' || id == null) {
        this.$message.error('请选择数据！');
        return;
      }
      this.$confirm('确认删除该地址吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        batchAddressDel(id).then((res) => {
          if (res.data.successFlg === true) {
            this.$message.success('删除成功！');
            this.searchShipAddress();
          } else {
            this.$message.error('删除失败！');
          }
        });
      }).catch(() => {
        this.listLoading = false;
      });
    },
    // 删除单条数据操作
    handelDelete (index, row) {
      this.$confirm('确认删除该地址吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        batchAddressDel([row.id]).then((res) => {
          this.listLoading = false;
          if (res.data.successFlg === true) {
            this.$message.success('删除成功！');
            this.searchShipAddress();
          } else {
            this.$message.error('删除失败！');
          }
        }).catch(() => {
          this.$message.error('数据有误，删除失败！');
          this.listLoading = false;
        });
      }).catch(() => {
        this.listLoading = false;
      });
    },
    // 设置默认
    setDefault (index, row) {
      this.$confirm('确认将该地址设为默认吗?', '提示', {
        type: 'info'
      }).then(() => {
        modifyIsDefault(row.id, this.userId, row.addressType).then((res) => {
          if (res.data.successFlg === true) {
            this.$message.success('恭喜，设置默认成功！');
            this.searchShipAddress();
          } else {
            this.$message.error('设置默认失败！');
          }
        });
      }).catch(() => {
        this.$message.error('数据有误，设置默认失败！');
      });
    },
    addressValue (value) {
      if (value) {
        return value;
      } else {
        return null;
      }
    },
    // 提交新增/修改
    handleSubmit (addressType) {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          // 若地址没有选到乡镇一级，且又不是那几个特殊地级市-提示错误
          if (!this.dialogForm.addressSelect[2]) {
            return this.$message.error('地址请至少选择到区县一级');
          }
          this.dialogForm.provinceId = this.addressValue(this.dialogForm.addressSelect[0]);
          this.dialogForm.cityId = this.addressValue(this.dialogForm.addressSelect[1]);
          this.dialogForm.countyId = this.addressValue(this.dialogForm.addressSelect[2]);
          this.dialogForm.townId = this.addressValue(this.dialogForm.addressSelect[3]);
          this.submitLoading = true;
          this.dialogForm.userId = this.userId;
          saveAddress(this.dialogForm).then((res) => {
            this.submitLoading = false;
            if (res.data.successFlg === true) {
              this.dialogFormVisible = false;
              this.$message.success('操作成功！');

              if (addressType === this.addressTypeShip) {
                this.searchShipAddress();
              }
              if (addressType === this.addressTypeSend) {
                this.searchSendAddress();
              }
              this.resetDialogForm();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            this.$message.error('数据有误，操作失败！');
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //* ***************************************************************发货地址**********************
    // 查询按钮
    sendHandleSearch () {
      if (!isEmpty(this.sendCondition.keyword) && isEmpty(this.sendCondition.keywordValue)) {
        this.$message.error('请输入查询关键字！');
        return;
      }
      this.searchSendAddress();
    },
    // 搜索收货地址列表
    searchSendAddress () {
      this.sendListLoading = true;
      let params = 'addressType=109002002 g0;';// 地址类型(固定发货地址类型）
      // 关键字
      if (!isEmpty(this.sendCondition.keyword) && !isEmpty(this.sendCondition.keywordValue)) {
        if (this.sendCondition.keyword === 'contactName') {
          params += 'contactName?' + this.sendCondition.keywordValue + ' g1;';
        }
        if (this.sendCondition.keyword === 'contactPhone') {
          params += 'contactPhone?' + this.sendCondition.keywordValue + ' g1;';
        }
        if (this.sendCondition.keyword === 'street') {
          params += 'collectAddressName?' + this.sendCondition.keywordValue + ' g1;';
        }
      }
      params += 'userId=' + this.userId + ' g2;';
      searchAddresses({
        page: this.sendCurrentPage,
        size: this.sendPageSize,
        filters: params,
        sorts: (this.sendSortProp === null ? '' : (this.sendSortOrder === 'ascending' ? '-' : '+') + this.sendSortProp)
      }).then((res) => {
        this.sendListLoading = false;
        if (res.data.successFlg === true) {
          this.sendAddressData = res.data.detailModelList;
          this.sendCurrentPage = res.data.currPage;
          this.sendTotal = res.data.totalCount;
          this.sendPageSize = res.data.pageSize;
        } else {
          this.$message.error('查询失败！');
        }
      }).catch(() => {
        this.$message.error('数据有误，查询失败！');
        this.sendListLoading = false;
      });
    },
    // 排序改变
    sendSortChange (o) {
      this.sendSortProp = o.prop;
      this.sendSortOrder = o.order;
      this.searchSendAddress();
    },
    // 多选框
    sendSelsChange (sels) {
      this.sendSels = sels;
    },
    // 每页几条操作
    sendHandleSizeChange (val) {
      this.sendPageSize = val;
      this.searchSendAddress();
    },
    // 第几页操作
    sendHandleCurrentChange (val) {
      this.sendCurrentPage = val;
      this.searchSendAddress();
    },
    // 重置查询条件
    sendResetCondition () {
      for (let p in this.sendCondition) {
        this.sendCondition[p] = null;
      }
    },
    // 批量删除
    sendHandelBathDelete () {
      let id = this.sendSels.map(item => item.id);
      if (id === '' || id == null) {
        this.$message.error('请选择数据！');
        return;
      }
      this.$confirm('确认删除该地址吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.sendListLoading = true;
        batchAddressDel(id).then((res) => {
          this.sendListLoading = false;
          if (res.data.successFlg === true) {
            this.$message.success('删除成功！');
            this.searchSendAddress();
          } else {
            this.$message.error('删除失败！');
          }
        });
      }).catch(() => {
        this.sendListLoading = false;
      });
    },
    // 删除单条数据操作
    sendHandelDelete (index, row) {
      this.$confirm('确认删除该地址吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        batchAddressDel([row.id]).then((res) => {
          this.listLoading = false;
          if (res.data.successFlg === true) {
            this.$message.success('删除成功！');
            this.searchSendAddress();
          } else {
            this.$message.error('删除失败！');
          }
        }).catch(() => {
          this.$message.error('数据有误，删除失败！');
          this.listLoading = false;
        });
      }).catch(() => {
        this.listLoading = false;
      });
    },
    // 设置默认
    sendSetDefault (index, row) {
      this.$confirm('确认将该地址设为默认吗?', '提示', {
        type: 'info'
      }).then(() => {
        modifyIsDefault(row.id, this.userId, row.addressType).then((res) => {
          if (res.data.successFlg === true) {
            this.$message.success('恭喜，设置默认成功！');
            this.searchSendAddress();
          } else {
            this.$message.error('设置默认失败！');
          }
        });
      }).catch(() => {
        this.$message.error('数据有误，设置默认失败！');
      });
    }
  },
  mounted () {
    this.searchShipAddress();
    this.$store.commit('initDict');
    this.searchSendAddress();
  }
};
</script>
